package com.example.communitysystem.advice;

import com.alibaba.fastjson.JSON;
import com.example.communitysystem.dto.ResultDTO;
import com.example.communitysystem.exception.CustomizeErrorCode;
import com.example.communitysystem.exception.CustomizeException;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class CustomizeExceptionHandler {
    @ExceptionHandler(Exception.class)
    ModelAndView handle(Throwable ex, Model model, HttpServletRequest request, HttpServletResponse response) {
        //获取请求的contentType
        String contentType = request.getContentType();
        //通过contentType判断是否返回json
        //前端传入的是json数据，后端返回json错误信息
        if("application/json".equals(contentType)){
            ResultDTO resultDTO = null;
            //返回Json
            if(ex instanceof CustomizeException){
                resultDTO =  ResultDTO.errorOf((CustomizeException)ex);
            }else{
                resultDTO = ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
            }
            try {
                response.setContentType("application/json");
                response.setStatus(200);
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                //把对象格式化成json对象
                writer.write(JSON.toJSONString(resultDTO));
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }else{
            //返回错误页面
            if (ex instanceof CustomizeException) {
                model.addAttribute("message", ex.getMessage());
            } else {
                model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());
            }

        }

        return new ModelAndView("error");
    }

}
